package com.thatvn.diemtinvietnam;

import java.util.ArrayList;
import java.util.HashMap;

import com.thatvn.diemtinvietnam.LazyAdapter;

import android.widget.ExpandableListView;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebSettings;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.view.Gravity;
import android.support.v4.app.*;
import android.app.ActionBar;

import com.thatvn.diemtinvietnam.SpinnerNavItem;
import com.thatvn.diemtinvietnam.TitleNavigationAdapter;

import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.app.ActionBar.OnNavigationListener;
import android.app.AlertDialog;
import android.app.Dialog;

import java.io.IOException;
import java.lang.Thread;
import java.net.URLEncoder;

import android.app.SearchManager;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.thatvn.diemtinvietnam.MyExpandableAdapter;
import com.thatvn.diemtinvietnam.TrendAdapter;
import com.thatvn.diemtinvietnam.jsonParseSearch;
import com.thatvn.diemtinvietnam.viewWeb;
//import com.thatvn.diemtinvietnam.MainActivity.showNewsFromUrlTask;
//import com.thatvn.diemtinvietnam.MainActivity.showNewsSearchFromUrlTask;
//import com.thatvn.diemtinvietnam.MainActivity.showNewsTrendFromUrlTask;
import com.thatvn.diemtinvietnam.jsonParse;
import com.thatvn.diemtinvietnam.jsonParseTrend;
import com.thatvn.diemtinvietnam.R;
import com.thatvn.diemtinvietnam.MainActivity;




//import com.thatvn.diemtinvietnam.NetworkUtil;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.graphics.Point;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.hardware.SensorManager;
import android.view.*;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.app.ExpandableListActivity; 

public class MainActivity extends ExpandableListActivity implements ActionBar.OnNavigationListener{

	private AlertDialog.Builder alertDialogBuilder;
	private AlertDialog alertDialog;
	private Thread thread;
	private int currentMenu=-1;
	// action bar
    private ActionBar actionBar;
    private MenuItem menuItem;
    // Title navigation Spinner data
    private ArrayList<SpinnerNavItem> navSpinner;
    private Context context; 
    // Navigation adapter
    private TitleNavigationAdapter adapterNavi;
    private Boolean loading=true;
    
    private ProgressDialog dialog;
    private Handler progressBarHandler = new Handler();
    private int progressBarStatus = 0;
    private Thread tPr;
    private jsonParseCategory jsonPCategory;//Lấy ra danh sách các Category từ domain
    private jsonParseDomain jsonPDomain;//Lấy các content của Category và domain tương ứng
    private jsonParse jsonP;
	private jsonParseSearch jsonPSearch;
	private jsonParseTrend jsonPTrend;
	static final String KEY_ID = "id";
	static final String KEY_TITLE = "title";
	static final String KEY_SOURCE = "maindomain";
	static final String KEY_DATE = "date";
	static final String KEY_LINK = "link";
	static final String KEY_IMAGE = "image";
	static final String KEY_RANKING = "ranking";
	static final String KEY_CATID = "catid";
	static final String KEY_TIMEDIFF = "timediff";
	static final String KEY_NAMERELATED = "nameRelated";
	static final String KEY_LINKRELATED = "linkRelated";
	static final String KEY_SOURCERELATED = "maindomainRelated";
	static final String KEY_IDRELATED = "idRelated";
	static final String KEY_IMAGERELATED = "imageRelated";
	static final String KEY_HASCONTENTRELATED = "hasContentRelated";
	static final String KEY_HASCONTENT = "hasContent";
	
	ExpandableListView expandableList;
	
	ListView list;
	LazyAdapter adapter;
    TrendAdapter adapterTrend;
    MyExpandableAdapter myExAdapter;
    public ArrayList<HashMap<String, String>> itemNewsListCategory;
    public ArrayList<HashMap<String, String>> itemNewsList;
    public ArrayList<Object> itemNewsListChild;
    public String[] allMenuItem = new String[]{"Xã Hội", "Thế Giới", "Kinh Tế", "Văn Hóa", "Thể Thao", "Pháp Luật", "Khoa Học", "Công Nghệ", "Ô Tô - Xe Máy", "Giáo Dục", "Sức Khỏe", "Giải Trí"};
	public String urlGetDetailNews=Config.domain+"/Home/getDetailNews?id=";
	public int maxDelay=120000;
	public long oldTime=0;
	private AdView adView;
	private static final String AD_UNIT_ID = "a153394068f232c";  
	public boolean isSearching=false;
	public String alertMessage="Không kết nối được, một trong các nguyên nhân sau:";
	public String connecMessage="-Kiểm tra lại đường truyền Internet.\r\n-Menu này chưa có nội dung, bạn chọn menu khác.\r\n-Website đang bảo trì.";
	//private OrientationEventListener myOrientationEventListener;
//	private Boolean isChangedRotation=false;
//	private Boolean isPreChangedRotation=false;
    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		if (!isChangedRotation) 
//			isChangedRotation=true;
//		else 
//			isChangedRotation=true;
		context=this.context;
		boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
		if (tabletSize) {
		    Config.isTablet=true;
		} else {
			Config.isTablet=false;
		}
		Log.e("isTabletisTabletisTabletisTabletisTabletisTablet", String.valueOf(Config.isTablet));
		dialog=new ProgressDialog(this);
		//setContentView(R.layout.activity_main);
		//showNewsFromUrl("http://diemtinvietnam.vn/Home/getHotNewsMobileApp");
		//checkNetworkStatus();
		Log.e("onCreateonCreateonCreateonCreateonCreateonCreate", "onCreateonCreateonCreateonCreateonCreate");
		isSearching=false;
			actionBar = getActionBar();        
			//Log.e("aaaaaaa", "2222222");
	        // Hide the action bar title
	        actionBar.setDisplayShowTitleEnabled(false); 
	        // Enabling Spinner dropdown navigation
	        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);         
	        // Spinner title navigation data
	        loadAllCategory();
	        //Log.e("aaaaaaa", "2");
	        actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg));
	        
	        currentMenu=-1;
	        //Log.e("aaaaaaa", "3");
	      //for Advertising
//	        adView = new AdView(this);
//		    adView.setAdSize(AdSize.BANNER);	   
//		    adView.setAdUnitId(AD_UNIT_ID);
//		    RelativeLayout rl = new RelativeLayout(this);
//		    RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(
//		        RelativeLayout.LayoutParams.FILL_PARENT, 
//		        RelativeLayout.LayoutParams.WRAP_CONTENT);
//		    lay.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);	    
//		    RelativeLayout layout = (RelativeLayout) findViewById(R.id.relativeLayoutMain);
//		    layout.addView(adView,lay);
//		    AdRequest adRequest = new AdRequest.Builder().build();
//		    adView.loadAd(adRequest);
		    //Log.e("aaaaaaa", "4");
//	        myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL){
//
//	         @Override
//	         public void onOrientationChanged(int arg0) {
//	          // TODO Auto-generated method stub
//	        	 isChangedRotation=true;
//	        	 Log.e("aaaaaaaaaaaaaaaaaaaaaa", "okokokokokokokokokokok");
//	         }};
	    
	}	
    public void loadAllCategory(){
    	navSpinner = new ArrayList<SpinnerNavItem>();
        navSpinner.add(new SpinnerNavItem("Tin nóng", R.drawable.category));
        navSpinner.add(new SpinnerNavItem("Điểm tin ngày", R.drawable.category));        
        navSpinner.add(new SpinnerNavItem("Đọc nhiều nhất", R.drawable.category));
        navSpinner.add(new SpinnerNavItem("Mới nhất", R.drawable.category));
        //Log.e("aaaaaaa", "33333");
        for(int i=0;i<allMenuItem.length;i++){
        	navSpinner.add(new SpinnerNavItem(allMenuItem[i], R.drawable.category));
        } 
        //Log.e("aaaaaaa", "444444");
        // title drop down adapter
        adapterNavi = new TitleNavigationAdapter(this.getBaseContext(), navSpinner);//getApplicationContext()//this.getBaseContext()
        //Log.e("aaaaaaa", "1");
        // assigning the spinner navigation     
        
        actionBar.setListNavigationCallbacks(adapterNavi, this);
    }
    public void loadMenuCategory(){
    	navSpinner = new ArrayList<SpinnerNavItem>();
    	itemNewsListCategory=jsonPCategory.getItemNewsListCategory();
        //Log.e("aaaaaaa", "33333");
        for(int i=0;i<itemNewsListCategory.size();i++){
        	navSpinner.add(new SpinnerNavItem(itemNewsListCategory.get(i).get("catname"), R.drawable.category));
        } 
        //Log.e("aaaaaaa", "444444");
        // title drop down adapter
        adapterNavi = new TitleNavigationAdapter(this.getBaseContext(), navSpinner);//getApplicationContext()//this.getBaseContext()
        //Log.e("aaaaaaa", "1");
        // assigning the spinner navigation     
        
        actionBar.setListNavigationCallbacks(adapterNavi, this);
    }
    
    public void  checkNetworkStatus(){

        final ConnectivityManager connMgr = (ConnectivityManager)
         this.getSystemService(Context.CONNECTIVITY_SERVICE);

         final android.net.NetworkInfo wifi =
         connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

         final android.net.NetworkInfo mobile =
         connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

         if( wifi.isAvailable() ){
        	 maxDelay=8000;
         }
         else if( mobile.isAvailable() ){
        	 maxDelay=15000;
         }
         else
         {
        	 maxDelay=8000;
         }
         //Log.e("checkNetworkStatus", String.valueOf(maxDelay));
    }
    //WHen Rotation
//    private boolean isRotaion=false;
//    @Override
//    public void onConfigurationChanged(Configuration newConfig)
//    {
//    	isRotaion=true;
//    }
    public void showExtProgram(String title,String message){
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

    	// 2. Chain together various setter methods to set the dialog characteristics
    	builder.setMessage(message)
    	       .setTitle(title)
    	       .setCancelable(false)
			   .setPositiveButton("Thoát",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, close
						// current activity							
						//MainActivity.this.finish();
				    	//System.exit(0);
					}
				 });

    	// 3. Get the AlertDialog from create()
    	alertDialog= builder.create();
    	alertDialog.show();
//    	int duration = Toast.LENGTH_SHORT;	
//		Toast toast = Toast.makeText(context, message, duration);
//		toast.show();
	}
//    private boolean isNetworkAvailable()
//    {
//    	
//
//    	return NetworkUtil.getConnectivityStatusString(MainActivity.this);
//
//    }
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.activity_main, menu);
		getMenuInflater().inflate(R.menu.main_activity_actions, menu);
		//MenuInflater inflater = getMenuInflater();
	    //inflater.inflate(R.menu.main_activity_actions, menu);
		// Associate searchable configuration with the SearchView
	    SearchManager searchManager =
	           (SearchManager) getSystemService(Context.SEARCH_SERVICE);
	    SearchView searchView =
	            (SearchView) menu.findItem(R.id.action_search).getActionView();
	    searchView.setSearchableInfo(
	            searchManager.getSearchableInfo(getComponentName()));
	    searchView.setSubmitButtonEnabled(false);
	    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
		{
			@Override
			public boolean onQueryTextSubmit(String query)
			{
				//ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "Diemtinvietnam.vn","Query="+query, true);
	            //dialog.show();
				if (isSearching==false){
					isSearching=true;
				}else{
					return true;
				}
				try{
					query=URLEncoder.encode(query, "UTF-8");
				}catch(Exception ex){
					
				}
				Config.typeLoad=0;
        		Config.typeView=0;
	            showNewsFromUrl(Config.domain+"/Title/searchMobileApp?keyword="+query);
				return true;
			}
			
			@Override
			public boolean onQueryTextChange(String newText)
			{
				return false;
			}
		});
	    return super.onCreateOptionsMenu(menu);
		//return true;
	}
	public void checkCondition(){
		if (jsonP.parsingComplete==false) 
			{
				loading=false;
				tPr.interrupt();
				progressBarStatus=-1;
				//dialog.setProgress(0);
				//dialog.cancel();
				dialog.dismiss();
			}
	}
	public void displayNewsSearchContent(){
		Log.e("displayNewsContent", "ok1");
		itemNewsList = new ArrayList<HashMap<String, String>>();		
	    itemNewsList=jsonPSearch.getItemNewsList();
	    Log.e("displayNewsContent", "ok2"+itemNewsList.size());
	    itemNewsListChild = new ArrayList<Object>();
	    Log.e("displayNewsContent", "ok3"+itemNewsListChild.size());
	    expandableList =getExpandableListView();//(ExpandableListView) findViewById(R.id.list);// getExpandableListView();//
	    		//getExpandableListView(); // you can use (ExpandableListView) findViewById(R.id.list)
	    Log.e("displayNewsContent", "ok4");
		//expandableList.setDividerHeight(2);
		Log.e("displayNewsContent", "ok41");
		expandableList.setGroupIndicator(null);
		Log.e("displayNewsContent", "ok42");
		expandableList.setClickable(true);

		Log.e("displayNewsContent", "ok5");

		myExAdapter = new MyExpandableAdapter(itemNewsList, itemNewsListChild,this,this.getBaseContext());
		Log.e("displayNewsContent", "ok6");
		
		myExAdapter.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
		expandableList.setAdapter(myExAdapter);
		expandableList.setOnChildClickListener(this);
		Log.e("displayNewsContent", "ok7");
	   
		expandableList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        	@Override
        	public void onGroupExpand(int groupPosition) {
        		ArrayList<HashMap<String,String>> child = new ArrayList<HashMap<String,String>>();
        		HashMap<String, String> news = new HashMap<String, String>();
        		//HashMap<String,String> news=HashMap<String,String> itemNewsList.get(groupPosition);       		
        		child=(ArrayList<HashMap<String,String>>) itemNewsListChild.get(groupPosition);        		
        		HashMap<String, String> newsChild = new HashMap<String, String>();
        		newsChild=child.get(0);
        		Log.e("setOnGroupExpandListener", "22222222222222");
        		if (newsChild.isEmpty() || newsChild.get("linkRelated").isEmpty()){//|| news.get("nameRelated").isEmpty()
        			newsChild=itemNewsList.get(groupPosition);
					String link=String.valueOf(newsChild.get("link"));
					String idNews=String.valueOf(newsChild.get("id"));
					String hasContent=String.valueOf(newsChild.get("hasContent"));	
					Log.e("setOnGroupExpandListener", link);
					Intent vi = new Intent(MainActivity.this, viewWeb.class);
					//Intent vi = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
					vi.putExtra("link", link);			
					vi.putExtra("id", idNews);
					vi.putExtra("hasContent", hasContent);
					//vi.setData(Uri.parse(link));
					startActivity(vi);
        		}
				//Log.e("Log","ket thuc  goi View Web");
				//return true;
			}
		});	
	}
	
	public void displayDomainNewsContent(){
		Log.e("displayNewsContent", "ok1");
		itemNewsList = new ArrayList<HashMap<String, String>>();		
	    itemNewsList=jsonPDomain.getItemNewsList();
	    //Log.e("displayNewsContent", "ok2"+itemNewsList.size());
	    itemNewsListChild = new ArrayList<Object>();		
	    itemNewsListChild=jsonPDomain.getItemNewsListChild();
	    //Log.e("displayNewsContent", "ok3"+itemNewsListChild.size());
	    expandableList = getExpandableListView();//(ExpandableListView) findViewById(R.id.list);//getExpandableListView();//(ExpandableListView) findViewById(R.id.list);
	    		//getExpandableListView(); // you can use (ExpandableListView) findViewById(R.id.list)
	    int[] colors = {0xCECECECE, 0xCECECECE, 0xCECECECE}; // red for the example
	    expandableList.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
	    expandableList.setDividerHeight(10);
	    expandableList.setPadding(10,10,10,10);
	    expandableList.setBackgroundColor(0xCECECECE);
	    
	    //Log.e("displayNewsContent", "ok4");
		//expandableList.setDividerHeight(2);
		//Log.e("displayNewsContent", "ok41");
		expandableList.setGroupIndicator(null);
		//Log.e("displayNewsContent", "ok42");
		expandableList.setClickable(true);

		//Log.e("displayNewsContent", "ok5");
		if (itemNewsList==null) return;
		myExAdapter = new MyExpandableAdapter(itemNewsList, itemNewsListChild,this,this.getBaseContext());
		//Log.e("displayNewsContent", "ok6");
		
		myExAdapter.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
		expandableList.setAdapter(myExAdapter);
		expandableList.setOnChildClickListener(this);
		//Log.e("displayNewsContent", "ok7");
	    //Log.e("displayNewsContent", "ok3");
	    //Log.e("itemNewsList", "ok1");	
	    //list=(ListView)findViewById(R.id.list);
	    //Log.e("displayNewsContent", "ok4");
		////////// Viec customize listview duoc thuc hien o LazayAdapter
        //adapter=new LazyAdapter(this, itemNewsList,this.getBaseContext());  
        //Log.e("displayNewsContent", "ok5");
        //list.setAdapter(adapter);
        //Log.e("displayNewsContent", "ok6");
        //Log.e("list.setAdapter(adapter);", "ok2");
	//}
		expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        	@Override
        	public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        		ArrayList<HashMap<String,String>> child = new ArrayList<HashMap<String,String>>();
        		child=(ArrayList<HashMap<String,String>>) itemNewsListChild.get(groupPosition);        		
        		HashMap<String, String> news = new HashMap<String, String>();
        		news=child.get(childPosition);
        		//Log.e("setOnChildClickListener", "111111");
        		if (!news.isEmpty() && !news.get("nameRelated").isEmpty()){//|| news.get("nameRelated").isEmpty()
					String link=String.valueOf(news.get("linkRelated"));
					String idNews=String.valueOf(news.get("idRelated"));	
					String hasContentRelated=String.valueOf(news.get("hasContentRelated"));
					//Log.e("setOnChildClickListener", link);
					Intent vi = new Intent(MainActivity.this, viewWeb.class);
					//Intent vi = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
					vi.putExtra("link", link);			
					vi.putExtra("id", idNews);
					vi.putExtra("hasContent", hasContentRelated);
					//vi.setData(Uri.parse(link));
					startActivity(vi);
        		}
				//Log.e("Log","ket thuc  goi View Web");
				return true;
			}
		});	
		expandableList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        	@Override
        	public void onGroupExpand(int groupPosition) {
        		ArrayList<HashMap<String,String>> child = new ArrayList<HashMap<String,String>>();
        		HashMap<String, String> news = new HashMap<String, String>();
        		//HashMap<String,String> news=HashMap<String,String> itemNewsList.get(groupPosition);       		
        		child=(ArrayList<HashMap<String,String>>) itemNewsListChild.get(groupPosition);        		
        		HashMap<String, String> newsChild = new HashMap<String, String>();
        		newsChild=child.get(0);
        		//Log.e("setOnGroupExpandListener", "22222222222222");
        		if (newsChild.isEmpty() || newsChild.get("linkRelated").isEmpty()){//|| news.get("nameRelated").isEmpty()
        			newsChild=itemNewsList.get(groupPosition);
					String link=String.valueOf(newsChild.get("link"));
					String idNews=String.valueOf(newsChild.get("id"));	
					String hasContent=String.valueOf(newsChild.get("hasContent"));
					
					//Log.e("setOnGroupExpandListener", link);
					Intent vi = new Intent(MainActivity.this, viewWeb.class);
					//Intent vi = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
					vi.putExtra("link", link);			
					vi.putExtra("id", idNews);
					vi.putExtra("hasContent", hasContent);
					//vi.setData(Uri.parse(link));
					startActivity(vi);
        		}
				//Log.e("Log","ket thuc  goi View Web");
				//return true;
			}
		});	
	}
	public void displayNewsContent(){
		//Log.e("displayNewsContent", "ok1");
		itemNewsList = new ArrayList<HashMap<String, String>>();		
	    itemNewsList=jsonP.getItemNewsList();
	    //Log.e("displayNewsContent", "ok2"+itemNewsList.size());
	    itemNewsListChild = new ArrayList<Object>();		
	    //itemNewsListChild=jsonP.getItemNewsListChild();//Không đọc tin liên quan nữa
	    //Log.e("displayNewsContent", "ok3"+itemNewsListChild.size());
	    expandableList = getExpandableListView();//(ExpandableListView) findViewById(R.id.list);//getExpandableListView();//(ExpandableListView) findViewById(R.id.list);
	    		//getExpandableListView(); // you can use (ExpandableListView) findViewById(R.id.list)
	    int[] colors = {0xCECECECE, 0xCECECECE, 0xCECECECE}; // red for the example
	    expandableList.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
	    expandableList.setDividerHeight(10);
	    expandableList.setPadding(10,10,10,10);
	    expandableList.setBackgroundColor(0xCECECECE);
	    
	    //Log.e("displayNewsContent", "ok4");
		//expandableList.setDividerHeight(2);
		//Log.e("displayNewsContent", "ok41");
		expandableList.setGroupIndicator(null);
		Log.e("displayNewsContent", "ok42");
		expandableList.setClickable(true);

		Log.e("displayNewsContent", "ok5");
		if (itemNewsList==null) return;
		myExAdapter = new MyExpandableAdapter(itemNewsList, itemNewsListChild,this,this.getBaseContext());
		Log.e("displayNewsContent", "ok6");
		
		myExAdapter.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
		expandableList.setAdapter(myExAdapter);
		expandableList.setOnChildClickListener(this);
		Log.e("displayNewsContent", "ok7");
	    //Log.e("displayNewsContent", "ok3");
	    //Log.e("itemNewsList", "ok1");	
	    //list=(ListView)findViewById(R.id.list);
	    //Log.e("displayNewsContent", "ok4");
		////////// Viec customize listview duoc thuc hien o LazayAdapter
        //adapter=new LazyAdapter(this, itemNewsList,this.getBaseContext());  
        //Log.e("displayNewsContent", "ok5");
        //list.setAdapter(adapter);
        //Log.e("displayNewsContent", "ok6");
        //Log.e("list.setAdapter(adapter);", "ok2");
	//}
		expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        	@Override
        	public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        		ArrayList<HashMap<String,String>> child = new ArrayList<HashMap<String,String>>();
        		child=(ArrayList<HashMap<String,String>>) itemNewsListChild.get(groupPosition);        		
        		HashMap<String, String> news = new HashMap<String, String>();
        		news=child.get(childPosition);
        		Log.e("setOnChildClickListener", "111111");
        		if (!news.isEmpty() && !news.get("nameRelated").isEmpty()){//|| news.get("nameRelated").isEmpty()
					String link=String.valueOf(news.get("linkRelated"));
					String idNews=String.valueOf(news.get("idRelated"));	
					String hasContentRelated=String.valueOf(news.get("hasContentRelated"));
					Log.e("setOnChildClickListener", link);
					Intent vi = new Intent(MainActivity.this, viewWeb.class);
					//Intent vi = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
					vi.putExtra("link", link);			
					vi.putExtra("id", idNews);
					vi.putExtra("hasContent", hasContentRelated);
					//vi.setData(Uri.parse(link));
					startActivity(vi);
        		}
				//Log.e("Log","ket thuc  goi View Web");
				return true;
			}
		});	
		expandableList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        	@Override
        	public void onGroupExpand(int groupPosition) {
        		ArrayList<HashMap<String,String>> child = new ArrayList<HashMap<String,String>>();
        		HashMap<String, String> news = new HashMap<String, String>();
        		//HashMap<String,String> news=HashMap<String,String> itemNewsList.get(groupPosition);       		
        		//child=(ArrayList<HashMap<String,String>>) itemNewsListChild.get(groupPosition);        		
        		HashMap<String, String> newsChild = new HashMap<String, String>();
        		newsChild=null;//child.get(0);
        		Log.e("setOnGroupExpandListener", "22222222222222");
        		if (newsChild==null){//|| news.get("nameRelated").isEmpty()
        			newsChild=itemNewsList.get(groupPosition);
					String link=String.valueOf(newsChild.get("link"));
					String idNews=String.valueOf(newsChild.get("id"));	
					String hasContent=String.valueOf(newsChild.get("hasContent"));
					
					Log.e("setOnGroupExpandListener", link);
					Intent vi = new Intent(MainActivity.this, viewWeb.class);
					//Intent vi = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
					vi.putExtra("link", link);			
					vi.putExtra("id", idNews);
					vi.putExtra("hasContent", hasContent);
					//vi.setData(Uri.parse(link));
					startActivity(vi);
        		}
				//Log.e("Log","ket thuc  goi View Web");
				//return true;
			}
		});	
	}
	public void displayNewsTrendContent(){
		Log.e("displayNewsTrendContent", "ok1");
		itemNewsList = new ArrayList<HashMap<String, String>>();		
	    itemNewsList=jsonPTrend.getItemNewsList();
	    Log.e("displayNewsTrendContent", "ok2 "+itemNewsList.size());
	    itemNewsListChild = new ArrayList<Object>();		
	    itemNewsListChild=jsonPTrend.getItemNewsListChild();
	    Log.e("displayNewsTrendContent", "ok3 "+itemNewsListChild.size());
	    expandableList = getExpandableListView();//(ExpandableListView) findViewById(R.id.list);//getExpandableListView();//(ExpandableListView) findViewById(R.id.list);
	    		//getExpandableListView(); // you can use (ExpandableListView) findViewById(R.id.list)
	    Log.e("displayNewsTrendContent", "ok4");
		//expandableList.setDividerHeight(2);
		Log.e("displayNewsTrendContent", "ok41");
		expandableList.setGroupIndicator(null);
		Log.e("displayNewsTrendContent", "ok42");
		expandableList.setClickable(true);

		Log.e("displayNewsTrendContent", "ok5");

		adapterTrend = new TrendAdapter(itemNewsList, itemNewsListChild,this,this.getBaseContext());
		Log.e("displayNewsTrendContent", "ok6");
		
		adapterTrend.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
		expandableList.setAdapter(adapterTrend);
		expandableList.setOnChildClickListener(this);
		Log.e("displayNewsTrendContent", "ok7");
	    //Log.e("displayNewsContent", "ok3");
	    //Log.e("itemNewsList", "ok1");	
	    //list=(ListView)findViewById(R.id.list);
	    //Log.e("displayNewsContent", "ok4");
		////////// Viec customize listview duoc thuc hien o LazayAdapter
        //adapter=new LazyAdapter(this, itemNewsList,this.getBaseContext());  
        //Log.e("displayNewsContent", "ok5");
        //list.setAdapter(adapter);
        //Log.e("displayNewsContent", "ok6");
        //Log.e("list.setAdapter(adapter);", "ok2");
	//}
		expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        	@Override
        	public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        		ArrayList<HashMap<String,String>> child = new ArrayList<HashMap<String,String>>();
        		child=(ArrayList<HashMap<String,String>>) itemNewsListChild.get(groupPosition);        		
        		HashMap<String, String> news = new HashMap<String, String>();
        		news=child.get(childPosition);
        		Log.e("setOnChildClickListener", "111111");
        		if (!news.isEmpty() && !news.get("link").isEmpty()){//|| news.get("nameRelated").isEmpty()
					String link=String.valueOf(news.get("link"));
					String idNews=String.valueOf(news.get("id"));
					String hasContent=String.valueOf(news.get("hasContent"));
					
					Log.e("setOnChildClickListener", link);
					Intent vi = new Intent(MainActivity.this, viewWeb.class);
					//Intent vi = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
					vi.putExtra("link", link);			
					vi.putExtra("id", idNews);
					vi.putExtra("hasContent", hasContent);
					//vi.setData(Uri.parse(link));
					startActivity(vi);
        		}
				//Log.e("Log","ket thuc  goi View Web");
				return true;
			}
		});	
		expandableList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        	@Override
        	public void onGroupExpand(int groupPosition) {
        		Log.e("displayNewsTrendContent", "22222222222222");
			}
		});
		Log.e("displayNewsTrendContent", "ok8");
	}
	private class showNewsFromDomainCategoryUrlTask extends AsyncTask<String, Void, String> {    	
        @Override
        protected String doInBackground(String... urls) {
              
            // params comes from the execute() call: params[0] is the url.
            try {
            	//Log.e("showNewsFromUrlTask", "1");
            	
            	Log.e("showNewsFromUrlTask", "ok1");
            	jsonPDomain=new jsonParseDomain(urls[0]);
        		Log.e("showNewsFromUrlTask", "ok2");
        		String re=jsonPDomain.fetchJSON();
        		Log.e("showNewsFromUrlTask", re+"--"+String.valueOf(jsonPDomain.getItemNewsList().size()));
        		//boolean result=
        		if (jsonPDomain.getItemNewsList()==null || jsonPDomain.getItemNewsList().size()<=0)
        		{
        			return "0";
        		} else
        		{
        			return re;
        		}
            } catch (Exception e) {
            	//Log.e("showNewsFromUrlTask", "can not download"+e.toString());
            	//tPr.interrupt();
            	//progressBarStatus=-1;
            	//dialog.setProgress(0);
            	//dialog.cancel();
            	//dialog.dismiss();
            	//showExtProgram(alertMessage,connecMessage);
            	//ResultDownloadWebpage=0;            	
            	return "0";
            }
        }
        
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            //textView.setText(result);
        	//try{
        		//if(dialog!=null) 
        	isSearching=false;
        	tPr.interrupt();
        	progressBarStatus=-1;
        	dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
        	if (result.equals("0")){ 
        		Log.e("onPostExecute", "can not download");
        		showExtProgram(alertMessage,connecMessage);
        	}else{        		
        		Log.e("onPostExecute", "ok");
        		//loadMenuCategory();
				//displayCategoryNewsContent();
        		displayDomainNewsContent();
        	}
        	//try{
        		//if(dialog!=null) dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
       }
    }
	private class showNewsFromDomainUrlTask extends AsyncTask<String, Void, String> {    	
        @Override
        protected String doInBackground(String... urls) {
              
            // params comes from the execute() call: params[0] is the url.
            try {
            	//Log.e("showNewsFromUrlTask", "1");
            	
            	Log.e("showNewsFromUrlTask", "ok1");
        		jsonPCategory=new jsonParseCategory(urls[0]);
        		Log.e("showNewsFromUrlTask", "ok2");
        		//boolean result=
                return jsonPCategory.fetchJSON();
            } catch (IOException e) {
            	//Log.e("showNewsFromUrlTask", "can not download");
            	//tPr.interrupt();
            	//progressBarStatus=-1;
            	//dialog.setProgress(0);
            	//dialog.cancel();
            	//dialog.dismiss();
            	//showExtProgram(alertMessage,connecMessage);
            	//ResultDownloadWebpage=0;            	
            	return "0";
            }
        }
        
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            //textView.setText(result);
        	//try{
        		//if(dialog!=null) 
        	isSearching=false;
        	//tPr.interrupt();
        	//progressBarStatus=-1;
        	//dialog.setProgress(0);
        	//dialog.cancel();
   			//dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
        	if (result.equals("0")){ 
        		Log.e("onPostExecute", "can not download");
        		showExtProgram(alertMessage,connecMessage);
        	}else{        		
        		Log.e("onPostExecute", "ok");
        		loadMenuCategory();
				//displayCategoryNewsContent();
        	}
        	//try{
        		//if(dialog!=null) dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
       }
    }
	private class showNewsFromUrlTask extends AsyncTask<String, Void, String> {    	
        @Override
        protected String doInBackground(String... urls) {
              
            // params comes from the execute() call: params[0] is the url.
            try {
            	//Log.e("showNewsFromUrlTask", "1");
            	
            	Log.e("showNewsFromUrlTask", "ok1");
        		jsonP=new jsonParse(urls[0]);
        		Log.e("showNewsFromUrlTask", "ok2");
        		//boolean result=
                return jsonP.fetchJSON();
            } catch (IOException e) {
            	//Log.e("showNewsFromUrlTask", "can not download");
            	//tPr.interrupt();
            	//progressBarStatus=-1;
            	//dialog.setProgress(0);
            	//dialog.cancel();
            	//dialog.dismiss();
            	//showExtProgram(alertMessage,connecMessage);
            	//ResultDownloadWebpage=0;            	
            	return "0";
            }
        }
        
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            //textView.setText(result);
        	//try{
        		//if(dialog!=null) 
        	isSearching=false;
        	tPr.interrupt();
        	progressBarStatus=-1;
        	//dialog.setProgress(0);
        	//dialog.cancel();
   			dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
        	if (result.equals("0")){ 
        		Log.e("onPostExecute", "can not download");
        		showExtProgram(alertMessage,connecMessage);
        	}else{        		
        		Log.e("onPostExecute", "ok");
				displayNewsContent();
        	}
        	//try{
        		//if(dialog!=null) dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
       }
    }
	private class showNewsSearchFromUrlTask extends AsyncTask<String, Void, String> {    	
        @Override
        protected String doInBackground(String... urls) {
              
            // params comes from the execute() call: params[0] is the url.
            try {
            	//Log.e("showNewsFromUrlTask", "1");
            	
            	Log.e("showNewsSearchFromUrlTask", "ok1");
            	jsonPSearch=new jsonParseSearch(urls[0]);
        		Log.e("showNewsSearchFromUrlTask", "ok2");
        		//boolean result=
                return jsonPSearch.fetchJSON();
            } catch (IOException e) {
            	//Log.e("showNewsSearchFromUrlTask", "can not download");
            	//tPr.interrupt();
            	//progressBarStatus=-1;
            	//dialog.setProgress(0);
            	//dialog.cancel();
            	//dialog.dismiss();
            	//showExtProgram(alertMessage,connecMessage);
            	//ResultDownloadWebpage=0;            	
            	return "0";
            }
        }
        
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            //textView.setText(result);
        	//try{
        		//if(dialog!=null) 
        	isSearching=false;
        	tPr.interrupt();
        	progressBarStatus=-1;
        	//dialog.setProgress(0);
        	//dialog.cancel();
   			dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
        	if (result.equals("0")){ 
        		Log.e("onPostExecute", "can not download");
        		showExtProgram(alertMessage,connecMessage);
        	}else{        		
        		Log.e("onPostExecute", "ok");
				displayNewsSearchContent();
        	}
        	//try{
        		//if(dialog!=null) dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
       }
    }
	public void showNewsSearchFromUrl(String url){
		Log.e("showNewsSearchFromUrl", "1");
		//dialog = ProgressDialog.show(MainActivity.this, Config.processInfo,Config.processMessage, true);
		progressBarStatus=0;
		dialog.setMessage(Config.processMessage);
		dialog.setCancelable(false);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setProgress(0);
		dialog.setMax(100);
		//dialog.setIndeterminate(true);
		dialog.show();

	   final int totalProgressTime = 100;

	   tPr = new Thread(){

	   @Override
	   public void run(){
	 
	      int jumpTime = 0;
	      while(jumpTime < totalProgressTime && progressBarStatus!=-1){
	         try {
	            sleep(1000);
	            jumpTime += 5;
	            progressBarStatus = jumpTime;
	            //dialog.setProgress(jumpTime);
	            // Update the progress bar
				  progressBarHandler.post(new Runnable() {
					public void run() {
						dialog.setProgress(progressBarStatus);
					}
				  });
	         } catch (InterruptedException e) {
	           // TODO Auto-generated catch block
	           e.printStackTrace();
	         }

	      }

	   }
	   };
	   tPr.start();
		new showNewsSearchFromUrlTask().execute(url);		
		Log.e("showNewsSearchFromUrl", "2");
		    
	}
	
	public void showNewsContentFromDomain(String url){
		Log.e("showNewsFromUrl", "1");
		//dialog = ProgressDialog.show(MainActivity.this, Config.processInfo,Config.processMessage, true);
		try
		{
			progressBarStatus=0;
			dialog.setMessage(Config.processMessage);
			dialog.setCancelable(false);
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setProgress(0);
			dialog.setMax(100);
			//dialog.setIndeterminate(true);
			dialog.show();
	
		   final int totalProgressTime = 100;
	
		   tPr = new Thread(){
	
		   @Override
		   public void run(){
		 
		      int jumpTime = 0;
		      while(jumpTime < totalProgressTime && progressBarStatus!=-1){
		         try {
		            sleep(1000);
		            jumpTime += 5;
		            progressBarStatus = jumpTime;
		            //dialog.setProgress(jumpTime);
		            // Update the progress bar
					  progressBarHandler.post(new Runnable() {
						public void run() {
							dialog.setProgress(progressBarStatus);
						}
					  });
		         } catch (InterruptedException e) {
		           // TODO Auto-generated catch block
		           e.printStackTrace();
		         }
	
		      }
	
		   }
		   };
		   tPr.start();
		   
			//dialog = ProgressDialog.show(LoadingScreenActivity.this,"Loading...","Loading application View, please wait...", false, false); 
			new showNewsFromDomainCategoryUrlTask().execute(url);		
			Log.e("showNewsFromUrl", "2");
		}catch(Exception ex)
		{
			
		}
	}
	public void showNewsFromUrl(String url){
		Log.e("showNewsFromUrl", "1");
		//dialog = ProgressDialog.show(MainActivity.this, Config.processInfo,Config.processMessage, true);
		progressBarStatus=0;
		dialog.setMessage(Config.processMessage);
		dialog.setCancelable(false);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setProgress(0);
		dialog.setMax(100);
		//dialog.setIndeterminate(true);
		dialog.show();

	   final int totalProgressTime = 100;

	   tPr = new Thread(){

	   @Override
	   public void run(){
	 
	      int jumpTime = 0;
	      while(jumpTime < totalProgressTime && progressBarStatus!=-1){
	         try {
	            sleep(1000);
	            jumpTime += 5;
	            progressBarStatus = jumpTime;
	            //dialog.setProgress(jumpTime);
	            // Update the progress bar
				  progressBarHandler.post(new Runnable() {
					public void run() {
						dialog.setProgress(progressBarStatus);
					}
				  });
	         } catch (InterruptedException e) {
	           // TODO Auto-generated catch block
	           e.printStackTrace();
	         }

	      }

	   }
	   };
	   tPr.start();
	   
		//dialog = ProgressDialog.show(LoadingScreenActivity.this,"Loading...","Loading application View, please wait...", false, false); 
		new showNewsFromUrlTask().execute(url);		
		Log.e("showNewsFromUrl", "2");
		    
	}
	//Lấy ra các danh mục chuyên đề menu của riêng từng báo
	public void showCategoryFromDomain(String url){
		Log.e("showNewsFromUrl", "1");
		//dialog = ProgressDialog.show(MainActivity.this, Config.processInfo,Config.processMessage, true);
//		progressBarStatus=0;
//		dialog.setMessage(Config.processMessage);
//		dialog.setCancelable(false);
//		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//		dialog.setProgress(0);
//		dialog.setMax(100);
//		//dialog.setIndeterminate(true);
//		dialog.show();

	   final int totalProgressTime = 100;

	   tPr = new Thread(){

	   @Override
	   public void run(){
	 
	      int jumpTime = 0;
	      while(jumpTime < totalProgressTime && progressBarStatus!=-1){
	         try {
	            sleep(1000);
	            jumpTime += 5;
	            progressBarStatus = jumpTime;
	            //dialog.setProgress(jumpTime);
	            // Update the progress bar
				  progressBarHandler.post(new Runnable() {
					public void run() {
						dialog.setProgress(progressBarStatus);
					}
				  });
	         } catch (InterruptedException e) {
	           // TODO Auto-generated catch block
	           e.printStackTrace();
	         }

	      }

	   }
	   };
	   tPr.start();
	   
		//dialog = ProgressDialog.show(LoadingScreenActivity.this,"Loading...","Loading application View, please wait...", false, false); 
	   new showNewsFromDomainUrlTask().execute(url);	
		Log.e("showNewsFromUrl", "2");
		    
	}
	private class showNewsTrendFromUrlTask extends AsyncTask<String, Void, String> {    	
        @Override
        protected String doInBackground(String... urls) {
              
            // params comes from the execute() call: params[0] is the url.
            try {
            	Log.e("showNewsTrendFromUrlTask", "ok1");
        		jsonPTrend=new jsonParseTrend(urls[0]);
        		Log.e("showNewsTrendFromUrlTask", "ok2");
                return jsonPTrend.fetchJSON();	
            } catch (IOException e) {
            	//Log.e("showNewsTrendFromUrlTask", "can not download");
            	//progressBarStatus=-1;
//            	tPr.stop();
            	//tPr.interrupt();
            	//dialog.setProgress(0);
            	//dialog.cancel();
            	//dialog.dismiss();
            	//showExtProgram(alertMessage,connecMessage);
            	//ResultDownloadWebpage=0;            	
            	return "0";
            }
        }
        
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            //textView.setText(result);
        	try{
        		if(dialog!=null) 
        			{
        				tPr.interrupt();
        				progressBarStatus=-1;
        				//dialog.setProgress(0);        				
        				//dialog.cancel();        				
        			 	dialog.dismiss();
        			}
        	}catch(Exception ex){
        		
        	}
        	if (result.equals("0")){ 
        		Log.e("onPostExecute", "can not download");
        		showExtProgram(alertMessage,connecMessage);
        	}else{        		
        		Log.e("onPostExecute", "ok");
				displayNewsTrendContent();
        	}
        	//try{
        		//if(dialog!=null) dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
       }
    }
	public void showNewsTrendFromUrl(String url){	

		Log.e("showNewsFromUrl", "1");
		//dialog = ProgressDialog.show(MainActivity.this, Config.processInfo,Config.processMessage, true);
		progressBarStatus=0;
		dialog.setMessage(Config.processMessage);
		dialog.setCancelable(false);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setProgress(0);
		dialog.setMax(100);
		//dialog.setIndeterminate(true);
		dialog.show();

	   final int totalProgressTime = 100;

	   tPr = new Thread(){

	   @Override
	   public void run(){
	 
	      int jumpTime = 0;
	      while(jumpTime < totalProgressTime && progressBarStatus!=-1){
	         try {
	            sleep(1000);
	            jumpTime += 5;
	            progressBarStatus = jumpTime;
	            //dialog.setProgress(jumpTime);
	            // Update the progress bar
				  progressBarHandler.post(new Runnable() {
					public void run() {
						dialog.setProgress(progressBarStatus);
					}
				  });
	         } catch (InterruptedException e) {
	           // TODO Auto-generated catch block
	           e.printStackTrace();
	         }

	      }

	   }
	   };
	   tPr.start();
	   
		new showNewsTrendFromUrlTask().execute(url);		
		Log.e("showNewsFromUrl", "2");
		    
	}
	@Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
   
		int catid=1;
//		if (isChangedRotation) {
			Log.e("bbbbbbbbbbbbbbbbbbb"+String.valueOf(currentMenu), "okokokokokokokokokokok"+String.valueOf(itemPosition));
//			isChangedRotation=false;
//			return false;
//		}
		if (currentMenu==itemPosition) return false;
		currentMenu=itemPosition;
		Log.e("bbbbbbbbbbbbbbbbbbb"+String.valueOf(currentMenu), "okokokokokokokokokokok"+String.valueOf(itemPosition));
		if (Config.typeView==0){//load tin tong hop
			switch (itemPosition) {
	        case 0:
	        	Config.typeLoad=0;
	        	showNewsFromUrl(Config.domain+"/Home/getHotNewsMobileApp2");
	            return true;
	        case 1:
	        	Config.typeLoad=0;
	        	showNewsFromUrl(Config.domain+"/Home/getAllNewsMobileApp2");        	
	            return true;
	        case 2:           
	        	Config.typeLoad=0;
	        	showNewsFromUrl(Config.domain+"/Home/getTopReadNewsMobileApp2");        	
	            return true;
	        case 3:           
	        	Config.typeLoad=0;
	        	showNewsFromUrl(Config.domain+"/Home/getLatestNewsMobileApp2");        	
	            return true;    
	        case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13:
	        	Config.typeLoad=1;
	        	catid=itemPosition-3;
	        	showNewsFromUrl(Config.domain+"/Home/getCatNewsMobileApp2?catid="+catid);
	        	return true;
	        case 14: case 15:    
	        	catid=itemPosition-2;
	        	Config.typeLoad=1;
	        	showNewsFromUrl(Config.domain+"/Home/getCatNewsMobileApp2?catid="+catid);
	        	return true;	
	        }
		}else{
			//Load cac chuyen muc o day
			showNewsContentFromDomain(Config.domain+"/Home/getContentRssFromUrlApp?indexDomain="+String.valueOf(Config.currentDomain)+"&indexCat="+String.valueOf(itemPosition));
			
		}
		//isChangedRotation=false;
        return false;
    }
	@Override
    public boolean onOptionsItemSelected(MenuItem item)
    {    
        switch (item.getItemId())
        {
        	case R.id.action_home:
        		Log.e("onOptionsItemSelectedonOptionsItemSelectedonOptionsItemSelected", "onOptionsItemSelectedonOptionsItemSelected");
        		currentMenu=0;
        		Config.typeLoad=0;
        		Config.typeView=0;
        		loadAllCategory();
        		showNewsFromUrl(Config.domain+"/Home/getHotNewsMobileApp2");
        		
        		//actionBar.setListNavigationCallbacks(adapterNavi, this);
            return true;         	
        	default:
            return super.onOptionsItemSelected(item);
        }
    } 
	public void showPopup(View v) {
	    PopupMenu popup = new PopupMenu(this, v);
	    MenuInflater inflater = popup.getMenuInflater();
	    inflater.inflate(R.menu.main_activity_actions, popup.getMenu());
	    //popup.inflate(R.menu.main_activity_actions);
	    popup.getMenu().clear();
	    popup.getMenu().add(0,0,0,"Tất cả các báo");
	    popup.getMenu().add(1,1,1,"Báo Vnexpress");
	    popup.getMenu().add(2,2,2,"Báo Dân Trí");
	    popup.getMenu().add(3,3,3,"Báo Zing");
	    popup.getMenu().add(4,4,4,"Báo 24h");
	    popup.getMenu().add(5,5,5,"Báo Kênh 14");
	    popup.getMenu().add(6,6,6,"Báo Đời sống Pháp luật");
	    popup.getMenu().add(7,7,7,"Báo Thể thao 24/7");
	    popup.getMenu().add(8,8,8,"Báo NgôiSao.net");
	    popup.getMenu().add(9,9,9,"Báo Vietnamnet");
	    popup.getMenu().add(10,10,10,"Báo Lao động");
	    popup.getMenu().add(11,11,11,"Báo Afamily");
	    popup.getMenu().add(12,12,12,"Báo Tuổi trẻ");
	    popup.getMenu().add(13,13,13,"Báo Thanh niên");
	    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
            	int index=item.getItemId()-1;
            	if (index>=0){
            		Config.typeView=1;
            		Config.currentDomain=index;
            		Config.currentDomainName=Utils.getDomainName(index);
            		currentMenu=0;
	                Toast.makeText(MainActivity.this,"Bạn đã chọn " + item.getTitle(),Toast.LENGTH_SHORT).show();
	                showCategoryFromDomain(Config.domain+"/Home/getCatListFromDomainRssApp?index="+ String.valueOf(index));
	                showNewsContentFromDomain(Config.domain+"/Home/getContentRssFromUrlApp?indexDomain="+String.valueOf(Config.currentDomain)+"&indexCat=0");
            	}else{
            		//currentMenu=1000;
            		currentMenu=0;
            		Config.typeLoad=0;
            		Config.typeView=0;
            		loadAllCategory();
            		showNewsFromUrl(Config.domain+"/Home/getHotNewsMobileApp2");
            	}
                //new showNewsFromDomainUrlTask().execute(Config.domain+"/Home/getCatListFromDomainRssApp?index="+ String.valueOf(item.getItemId()));
                //loadMenuCategory();
                return true;
            }
        });
	    
	    popup.show();
	}
	public void onBackPressed()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

    	// 2. Chain together various setter methods to set the dialog characteristics
    	builder.setMessage("Bạn có muốn thoát chương trình?")    	       
    	       .setCancelable(false)
			   .setPositiveButton("Có",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, close
						// current activity		
						/* This code assumes you are inside an activity */
//						final Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
//						final Intent rateAppIntent = new Intent(Intent.ACTION_VIEW, uri);
//
//						if (getPackageManager().queryIntentActivities(rateAppIntent, 0).size() > 0)
//						{
//						    startActivity(rateAppIntent);
//						}
//						else
//						{
//						    /* handle your error case */
//						}
						MainActivity.this.finish();
				    	System.exit(0);
					}
				 }).setNegativeButton("Không",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, close
						// current activity
						alertDialog.hide();
					}
				 });

    	// 3. Get the AlertDialog from create()
    	alertDialog= builder.create();
    	alertDialog.show();
		
	}
	//public void searchNews(){
		//Log.e("searchNews", "1");
		//TextView keyword = (TextView)findViewById(R.id.keyword);
		//Log.e("searchNews", "2");
		//String keywordurl = "";
		//try{
			//keywordurl=URLEncoder.encode(keyword.getText().toString(), "UTF-8");		
		//}catch(Exception ex){
			
		//}
		//Log.e("searchNews", "3");
		//setContentView(R.layout.activity_main);
		//Log.e("searchNews", "4");
		//showNewsFromUrl("http://diemtinvietnam.net/Title/searchMobileApp?keyword="+keywordurl);
		//Log.e("searchNews", "5");
	//}
}
